package com.raymond.thread.manager.pool;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2020-05-26 15:35
 */

@Configuration
@ConfigurationProperties(prefix = "java.default.thread.pool")
@Data
@Component
public class DefaultThreadPool {
    /** 核心线程数（默认线程数）*/
    private int corePoolSize = 20;
    /** 最大线程数 */
    private int maxPoolSize = 30;
    /** 允许线程空闲时间（单位：默认为秒）*/
    private int keepAliveTime = 1;
    /** 缓冲队列数 */
    private int queueCapacity = 1000;
    /**线程池的容器bean名称**/
    public static final String THREAD_POOL_NAME = "javaDbThreadExecutor";
    /**线程名称**/
    public static final String THREAD_NAME = "javaDbThread";

    @Bean
    public ThreadPoolTaskExecutor javaDbThreadExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveTime);
        executor.setThreadNamePrefix("Java-Db-Server-Executor-");
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}
